'use strict';

const BaseController = require('./base');
const { createRule } = require('../validator/questionAnswer')
const { success, commonErr } = require('../extend/helper');

class QuestionController extends BaseController {

    /**
     * 列表
     */
    async list() {
        const page = parseInt(this.ctx.query.page) ? parseInt(this.ctx.query.page) : 0;
        const size = parseInt(this.ctx.query.size) ? parseInt(this.ctx.query.size) : 15;
        const { rows, count } = await this.ctx.model.QuesttionAnswer.findAndCountAll({
            offset: page * size,
            limit: size
        });
        success({
            beans: {
                rows, count, page, size

            }
        })

    }

    /**
     * 新增
     */
    async add() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(createRule, data);
        error && commonErr({ beans: error });
        const res = await this.ctx.model.QuesttionAnswer.create(data);
        success();
    }

    /**
     * 编辑
     */
    async edit() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(createRule, data);
        error && commonErr({ beans: error });
        const id = this.ctx.params.id;
        await this.ctx.model.QuesttionAnswer.update(data, { where: { id } });
        success();
    }

    /**
     * 删除
     */
    async delete() {
        const question = await this.getObject();
        question.destroy();
        success();
    }

    
    async getObject() {
        const id = this.ctx.params.id;
        const question = await this.ctx.model.QuesttionAnswer.findByPk(id);
        if (!question) {
            commonErr(`问答例子不存在`);
        }
        return question;
    }

}

module.exports = QuestionController;
